import {
  version,
  appName,
  appCNName,
  c,
  apiHeader,
  getTokenUrl,
  getCommonUrl,
  postImgs,
  postSave,
} from './config.js'
import {
  wxLogin,
  setStorage
} from './wxTool.js'
import {
  isOverdue
} from './util.js'

//判断用户token
const isUserToken = () => {
  const userToken = wx.getStorageSync('Token')
  if (isOverdue(userToken.time)) {
    getApp().globalData.token = userToken.Token
    getApp().globalData.appName = appName
    return userToken.Token
  }
}
//获取用户token
const getUserToken = () => {
  const promise = new Promise(function (resolve, reject) {
    wxLogin().then(res => {
      console.log('resres', res)
      wx.request({
        url: getTokenUrl,
        data: {
          appName,
          code: res.code
        },
        method: 'post',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: resolve
      })
    })
  })
  return promise;
}

//http请求
const request = (url, data, method) => {
  const promise = new Promise(function (resolve, reject) {
    const token = isUserToken()
    if (token) {
      wx.request({
        url: url,
        data: Object.assign(data, {
          token: token,
          appName,
          c: c,
          version: version,
        }),
        method: method,
        header: {
          'content-type': 'application/json'
        },
        success: resolve,
        fail: reject
      })
    } else {
      getUserToken().then(res => {
        const token = res.data.data.token
        const time = new Date().getTime()
        const ads = res.data.data.advertise
        const ads2 = res.data.data.advertise2
        getApp().globalData.token = token
        wx.request({
          url: url,
          data: Object.assign(data, {
            token: token,
            appName,
            c: c,
            version: version,
          }),
          method: method,
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: resolve,
          fail: reject
        })
        if (res.data.data.uid) {
          const uid = res.data.data.uid
          setStorage('uid', {
            uid,
          })
        }
        if (res.data.data.shareData) {
          const shareData = res.data.data.shareData
          setStorage('shareData', {
            shareData,
          })
        }
        setStorage('Token', {
          Token: token,
          time: time
        })
        setStorage('advertise', {
          advertise: ads
        })
        setStorage('advertise2', {
          advertise: ads2
        })
      })
    }
  })
  return promise;
}


// 获取首页数据
const getData = (data) => {
  return request(getCommonUrl, data, 'get')
}
const pushImgs = (data) => {
  return request(postImgs, data, 'post')
}
const pushSave = (data) => {
  return request(postSave, data, 'post')
}

module.exports = {
  getData,
  pushImgs,
  pushSave,
} 